import React from 'react';
import ReactDom from 'react-dom';
import { BaseTable, useTablePipeline, features } from 'ali-react-table';
import styled, { StyleSheetManager } from 'styled-components';

const hoverColor = 'rgba(255, 255, 255, 0.1)';
const StyledBaseTable = styled(BaseTable)`
  --font-size: 12px;
  --line-height: 1;
  --row-height: 28px;
  --cell-padding: 0;

  --bgcolor: #4d535d;
  --hover-bgcolor: #35393f;
  --highlight-bgcolor: #262626;
  --color: #d8d8d8;
  --header-color: #888e95;
  // --header-bgcolor: #2a2f36;
  --lock-shadow: var(--ant-cus-base_bg_black_a25) 0 0px 6px 2px;

  --border-color: #727272;
  --cell-border-vertical: none;
  --header-cell-border-vertical: none;
  tr > td:nth-child(1),
  tr > td:nth-child(2) {
    padding: 0 5px;
  }
  tr.first th {
    border-top: none;
  }
  td:not(.lock-left):hover {
    background: ${hoverColor} !important;
  }
  th {
    height: 50px !important;
    line-height: 21px !important;
  }
  .expansion-cell {
    width: 100%;
    height: 100%;
  }
  .art-sticky-scroll {
    display: none !important;
  }
  *::-webkit-scrollbar {
    width: 0 !important;
    height: 0 !important;
  }
  a {
    color: #18a0fb !important;
  }
`;

export default ({
  dataSource,
  columns,
  columnWidth,
  startIndex,
  hoverColIndex,
  onChangeHoverColIndex,
}) => {
  const tableRef = React.useRef();
  const lockNum = 2; // 锁列数量

  React.useEffect(() => {
    scrollTo(startIndex);
  }, [startIndex]);

  const pipeline = useTablePipeline({ components: {} })
    .input({ columns, dataSource })
    .use(
      features.columnRangeHover({
        hoverColor: hoverColor,
        headerHoverColor: hoverColor,
        hoverRange:
          hoverColIndex === -1
            ? { start: -1, end: -1 }
            : { start: hoverColIndex + lockNum, end: hoverColIndex + lockNum + 1 },
        onChangeHoverRange: (r) => {
          const n = r.start;
          let idx = n < lockNum ? -1 : n - lockNum;
          onChangeHoverColIndex?.(idx);
        },
      }),
    )
    .primaryKey('id')
    .use(features.treeMode());

  const scrollTo = (i) => {
    if (!tableRef.current) return;
    // eslint-disable-next-line react/no-find-dom-node
    const tableBody = ReactDom.findDOMNode(tableRef.current).querySelector('.art-table-body');
    tableBody.scrollLeft = i * columnWidth;
  };

  return (
    <StyleSheetManager disableCSSOMInjection>
      <StyledBaseTable
        ref={tableRef}
        useVirtual={true}
        defaultColumnWidth={columnWidth}
        style={{ width: '100%' }}
        {...pipeline.getProps()}
      />
    </StyleSheetManager>
  );
};
